package org.elzat.healthboxgatewayapp.service.implV1;

import lombok.AllArgsConstructor;
import org.elzat.healthboxgatewayapp.dto.HealthBoxUserEntity;
import org.elzat.healthboxgatewayapp.dto.HealthBoxUserVO;
import org.elzat.healthboxgatewayapp.repository.HealthBoxUserRepository;
import org.elzat.healthboxgatewayapp.service.HealthBoxUserModifyService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@AllArgsConstructor
public class HealthBoxUserModifyServiceV1 implements HealthBoxUserModifyService {

    private final HealthBoxUserRepository userRepo;
    private final PasswordEncoder encoder;

    @Override
    public Boolean hasDuplicateUserPhone(String userPhone) {
        return userRepo.existsByUserPhone(userPhone);
    }

    @Override
    public Boolean hasDuplicateIdNumber(String idNumber) {
        return userRepo.existsByIdNumber(idNumber);
    }

    @Override
    public HealthBoxUserVO register(HealthBoxUserVO vo, String password) {
        HealthBoxUserEntity entity = HealthBoxUserEntity.builder()
                .id(null)
                .userPhone(vo.getUserPhone())
                .role(vo.getRole().name())
                .idNumber(vo.getIdNumber())
                .password(encoder.encode(password))
                .locked(false)
                .name(vo.getName())
                .build();
        entity = userRepo.save(entity);
        return entity.toVO();
    }

    @Override
    public Boolean lockUserByUserId(Long userId) {
        return changeLocks(userId, true);
    }

    @Override
    public Boolean unlockUserByUserId(Long userId) {
        return changeLocks(userId, false);
    }

    private Boolean changeLocks(Long userId, boolean lock) {
        Optional<HealthBoxUserEntity> maybe = userRepo.findById(userId);
        if (!maybe.isPresent()) return false;
        HealthBoxUserEntity entity = maybe.get();
        entity.setLocked(lock);
        userRepo.save(entity);
        return true;
    }
}
